﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Collections.Generic;

namespace Facebook.Windows
{
    /// <summary>
    /// Interaction logic for FacebookLoginPage.xaml
    /// </summary>
    public partial class Login : Window
    {
        private string _loginUrl;
        private DispatcherTimer sourceCheckerTimer = new DispatcherTimer();

        /// <summary>
        /// Constructor to receive login URL parameter
        /// </summary>
        /// <param name="loginUrl"></param>
        public Login(string loginUrl)
        {
            _loginUrl = loginUrl;
            InitializeComponent();

            sourceCheckerTimer.Interval = TimeSpan.FromMilliseconds(500);
            sourceCheckerTimer.Tick += new EventHandler(sourceCheckerTimer_Tick);

            this.Loaded += new RoutedEventHandler(Login_Loaded);
            this.Closing += new System.ComponentModel.CancelEventHandler(Login_Closing);

            uiFrameLogin.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(uiFrameLogin_LoadCompleted);

            
        }

        void uiFrameLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            sourceCheckerTimer.Start();
        }

        void sourceCheckerTimer_Tick(object sender, EventArgs e)
        {
            string currentSource = CurrentPageSource;

            //Check the source and close as needed
			if
			(
				currentSource.StartsWith(WEI_Share.Properties.Resources.FacebookNextLoginParameter) ||
				currentSource.StartsWith(WEI_Share.Properties.Resources.FacebookCancelLoginParameter)
			)
			{
				sourceCheckerTimer.Stop();
				this.Close();
			}
        }




        /// <summary>
        /// Property to indicate if authentication with facebook was a success
        /// </summary>
        public bool AuthenticatedSuccessfully
        {
            get
            {
                if(CurrentPageSource.StartsWith(WEI_Share.Properties.Resources.FacebookNextLoginParameter)) return true; // if its at this page, we've auth'd successfully
                return false; // cant find the success page, cant indicate a successful auth - no return false.
            }
        }

        /// <summary>
        /// Gets the current page source
        /// </summary>
        public string CurrentPageSource
        {
            get
            {
                string currentSource = string.Empty;
                if (uiFrameLogin.Content.GetType() == typeof(WebBrowser))
                {
                    WebBrowser webBrowser = (WebBrowser)uiFrameLogin.Content;
                    if (webBrowser.Source != null)
                        return webBrowser.Source.ToString();
                }

                return string.Empty;
            }
        }

        /// <summary>
        /// Gets the current page source
        /// </summary>
        public string CurrentPageSourceQuery
        {
            get
            {
                string currentSource = string.Empty;
                if (uiFrameLogin.Content.GetType() == typeof(WebBrowser))
                {
                    WebBrowser webBrowser = (WebBrowser)uiFrameLogin.Content;
                    if (webBrowser.Source != null)
                    {
                        string query = null;

                        if (webBrowser.Source.Query.StartsWith("?"))
                            query = webBrowser.Source.Query.Substring(1);
                        else
                            query = webBrowser.Source.Query;

                        return System.Web.HttpUtility.UrlDecode(query);
                    }
                }

                return null;
            }
        }

        /// <summary>
        /// Load the wait page while we load the login page "in the background"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Login_Loaded(object sender, RoutedEventArgs e)
        {
            var uiPgWait = new WaitPage();
            uiFrameWait.Content = uiPgWait;

			uiFrameLogin.Source = new Uri(_loginUrl);  // Navigate to the login URL provided once the WPF page loads, the navigated event will automagically surface this over the wait page
        }

        /// <summary>
        /// When the window closes, check the login has been successful, if not, by jove, let the user know!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Login_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!AuthenticatedSuccessfully)
            {
                if (MessageBox.Show("You have not logged in properly, continue to exit?", "Error", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

    }
}
